import { z } from "zod"; import { guarded, json, body } from "@/lib/api"; import { sql } from "@/lib/db"; export const GET = guarded<{ id: string }>(async (req, { params }) => { const a = await sql`SELECT * FROM artifacts WHERE id = ${params.id}`; if (!a[0]) return json({ error: "Introuvable" }, { status: 404 }); const versions = await sql`SELECT id, version, created_at, saved FROM artifacts WHERE root_id = ${a[0].root_id} ORDER BY version`; if (req.nextUrl.searchParams.get("raw") === "1") return new Response(a[0].content, { headers: { "content-type": "text/plain; charset=utf-8", "content-disposition": `attachment; filename="${String(a[0].title).replace(/[^\w.-]/g, "_")}.${ext(a[0].type, a[0].language)}"` } }); return json({ artifact: a[0], versions }); }); export const PATCH = guarded<{ id: string }>(async (req, { params }) => { const b = await body(req, z.object({ saved: z.boolean().optional(), projectId: z.string().nullable().optional(), title: z.string().min(1).max(120).optional() })); await sql`UPDATE artifacts SET saved = COALESCE(${b.saved ?? null}, saved), title = COALESCE(${b.title ?? null}, title), project_id = CASE WHEN ${b.projectId !== undefined} THEN ${b.projectId ?? null} ELSE project_id END WHERE id = ${params.id}`; return json({ ok: true }); }); export const DELETE = guarded<{ id: string }>(async (_req, { params }) => { await sql`DELETE FROM artifacts WHERE id = ${params.id}`; return json({ ok: true }); }); function ext(type: string, lang: string | null) { return ({ html: "html", svg: "svg", mermaid: "mmd", react: lang === "jsx" ? "jsx" : "tsx", python: "py", typescript: "ts", markdown: "md", table: "csv", chart: "json" } as Record)[type] ?? "txt"; }